package com.rovinj_server.view;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.rovinj_server.R;
import com.rovinj_server.adapter.InventoryRecordAdapter;
import com.rovinj_server.db.DBManager;
import com.rovinj_server.entity.Inventory;
import com.rovinj_server.utisl.DialogUtil;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * 扫描记录弹出框
 *
 * @author http://yecaoly.taobao.com
 */
@SuppressLint("CommitPrefEdits")
public class InventoryRecordPopWindow implements OnDismissListener, OnClickListener {
    private final static String TAG = "SelectScanRecord";
    private TextView tv_selectednum, tv_znum, tv_nodata;
    private Button btn_rescan;
    private ImageView pop_del;
    private PopupWindow popupWindow;
    private OnSelectScanRecordItemClickListener listener;
    private ListView lv_orderInfo;
    private Context context;
    private ArrayList<Map> mlist = new ArrayList<Map>();
    private ArrayList<Map> scanRecord = new ArrayList<Map>();
    private InventoryRecordAdapter adapter;
    private int checkNum;
    public static boolean isRescaned = false;
    public static ArrayList<Map> deleteRecord;
    private int deleteNums = 0;
    private ProgressDialog accessNetDialog;

    private List<Inventory>  mInventotyData=new ArrayList<>();


    public InventoryRecordPopWindow(Context context, List<Inventory>  Data) {
        this.context = context;
        this.mInventotyData = Data;

        View view = LayoutInflater.from(context).inflate(R.layout.select_scan_record_adapter_popwindow, null);
        tv_selectednum = (TextView) view.findViewById(R.id.selectednum);
        tv_znum = (TextView) view.findViewById(R.id.znum);
        //   tv_nodata = (TextView) view.findViewById(R.id.nodata);
        pop_del = (ImageView) view.findViewById(R.id.tv_pop_del);
        btn_rescan = (Button) view.findViewById(R.id.rescan);
        btn_rescan.setOnClickListener(this);
        pop_del.setOnClickListener(this);
        deliveryEPC();
        lv_orderInfo = (ListView) view.findViewById(R.id.lv_pop_orderinfo);
        lv_orderInfo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Map<String, String> m = (Map<String, String>) lv_orderInfo.getItemAtPosition(position);
                Inventory m = (Inventory) lv_orderInfo.getItemAtPosition(position);
                InventoryRecordAdapter.ViewHolder holder = (InventoryRecordAdapter.ViewHolder) view.getTag();
                holder.cb.toggle();
                adapter.getIsSelected().put(position, holder.cb.isChecked());
                // 调整选定条目
                if (holder.cb.isChecked() == true) {
                    checkNum++;
                } else {
                    checkNum--;
                }
                if (checkNum > 0) {
                    btn_rescan.setEnabled(true);
                    //    btn_rescan.setBackgroundResource(R.color.default_button_Normal);
                } else {
                    btn_rescan.setEnabled(false);
                    //  btn_rescan.setBackgroundResource(R.color.default_button_disabled);
                }
                // 用TextView显示
                tv_selectednum.setText("已选中" + checkNum + "项");
            }
        });

        popupWindow = new PopupWindow(view, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        //设置popwindow的动画效果
        popupWindow.setAnimationStyle(R.style.popWindow_anim_style);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popupWindow.setOnDismissListener(this);// 当popWindow消失时的监听

        //获取扫描记录
        Message message = new Message();
        message.what = 0;
        netHandler.sendMessage(message);
    }


    Handler netHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 99: {
                    dissmiss();
                    break;
                }
                //获取扫描记录
                case 0: {
                    DialogUtil.dismissDialog(accessNetDialog);
                    if (mInventotyData != null && mInventotyData.size() > 0) {
                        adapter = new InventoryRecordAdapter(context, mInventotyData);
                        lv_orderInfo.setAdapter(adapter);
                        lv_orderInfo.setVisibility(View.VISIBLE);
                        //  tv_nodata.setVisibility(View.GONE);
                        tv_znum.setText("共" + mInventotyData.size() + "项");
                    } else {
                        lv_orderInfo.setVisibility(View.GONE);
                        //  tv_nodata.setVisibility(View.VISIBLE);
                    }

                    // adapter.notifyDataSetChanged();
                    break;
                }
                case 1: {
                    DialogUtil.dismissDialog(accessNetDialog);
                    Bundle bundle = msg.getData();

                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    builder.setTitle("提示");
                    builder.setMessage("删除扫描记录");
                    builder.setNegativeButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ////////					deliveryEPC(mAndroidInfos);
                            dialog.dismiss();
                            dissmiss();
                        }
                    }).create();
                    builder.setCancelable(false);
                    builder.show();
                    break;
                }
                case 3: {
                    DialogUtil.dismissDialog(accessNetDialog);
                    String obj = (String) msg.obj;
                    adapter.notifyDataSetChanged();
                    Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }
    };


    public interface OnSelectScanRecordItemClickListener {
        /**
         * 设置点击确认按钮时监听接口
         */
        public void onSelectClickOKPop();

        /**
         * 设置点击关闭按钮时监听接口
         */
        public void onSelectClickDismissPop();
    }

    /**
     * 设置监听
     */
    public void setOnSelectScanRecordItemClickListener(OnSelectScanRecordItemClickListener listener) {
        this.listener = listener;
    }


    // 当popWindow消失时响应
    @Override
    public void onDismiss() {
        listener.onSelectClickDismissPop();
    }

    /**
     * 弹窗显示的位置
     */
    public void showAsDropDown(View parent) {
        popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.update();
    }

    /**
     * 消除弹窗
     */
    public void dissmiss() {
        popupWindow.dismiss();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_pop_del:
                listener.onSelectClickDismissPop();
                dissmiss();
                break;
            case R.id.rescan:
                dialog();
                break;
            default:
                break;
        }
    }

    /***
     * 获取扫描记录
     **/
    private void deliveryEPC() {

    }

    /**
     * 弹出对话框提示是否确定要重扫
     */
    private void dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage("删除扫描记录？");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                deleteSscanning();
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    // 删除扫描扫描记录

    public void deleteSscanning() {

        HashMap<Integer, Boolean> isSelected = adapter.getIsSelected();
        final List<Inventory> mDataScanng = new ArrayList<>();
        Iterator iter = isSelected.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            int key = (int) entry.getKey();
            boolean val = (boolean) entry.getValue();
            if (val) {
                mDataScanng.add(mInventotyData.get(key));


            }
        }
         accessNetDialog = new ProgressDialog(context);
        accessNetDialog.setCanceledOnTouchOutside(false);
        DialogUtil.showDialog(accessNetDialog, "正在获取数据，请稍候...");

        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager(context);
                dbManager.copyDBFile();
                for (int i = 0; i < mDataScanng.size(); i++) {
                    int id = mDataScanng.get(i).getId();
                    dbManager.deleteSubIdNull(id+"");
                    dbManager.deleteInventoryIdData(id+"");



                }
                mInventotyData.clear();
                mInventotyData=dbManager.findDataList();
              adapter.setList(mInventotyData);
                Message message = new Message();
                message.what=3;
                netHandler.sendMessage(message);
            }
        }).start();

    }

}
